271D - Good Substrings - CodeForces Solution


data structures strings *1800

Please click on ads to support us..

Python Code:




import collections
import time
import os
import sys
import bisect
import heapq
from typing import List


def solve(S, B, K):
    MOD = (1 << 50) + 9
    s = set()

    N = len(S)
    pow = [1 for _ in range(N+1)]
    for i in range(1, N+1):
        pow[i] = pow[i-1] * 26
        pow[i] %= MOD
        for i in range(N-1, -1, -1):
        k, h = 0, 0
        for j in range(i, -1, -1):
            ch = S[j]
            if B[ch]:
                k += 1
            if k > K:
                                break
            h += (ord(ch) - ord('a') + 1) * pow[i-j]
            h %= MOD
                        s.add(h)
        return len(s)


S = input()
B = list(input())
K = int(input())

B = {chr(ord('a') + i): False if B[i] == '1' else True for i in range(26)}
print(solve(S, B, K))













C++ Code:

#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;

char s[2000], che[30];
pair<ULL, ULL> a[2260000];

int main()
{
    scanf("%s%s", s, che);
    int n = 0, k;
    scanf("%d", &k);
    for (int i = 0; s[i]; i++)
    {
        int cnt = 0;
        ULL h1 = 5381, h2 = 0;
        for (int j = i; s[j]; j++)
        {
            if (che[s[j] - 'a'] == '0')
                cnt++;
            if (cnt > k)
                break;
            h1 = h1 * 33ll + s[j];
            h2 = h2 * 131ll + s[j];
            a[n++] = make_pair(h1, h2);
        }
    }
    sort(a, a + n);
    printf("%d\n", (int)(unique(a, a + n) - a));
}


Comments

Submit
0 Comments
More Questions

97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function
1920. Build Array from Permutation
494. Target Sum
797. All Paths From Source to Target
1547B - Alphabetical Strings
1550A - Find The Array
118B - Present from Lena
27A - Next Test
785. Is Graph Bipartite
90. Subsets II
1560A - Dislike of Threes
36. Valid Sudoku
557. Reverse Words in a String III
566. Reshape the Matrix
167. Two Sum II - Input array is sorted
387. First Unique Character in a String
383. Ransom Note
242. Valid Anagram
141. Linked List Cycle
21. Merge Two Sorted Lists
203. Remove Linked List Elements
733. Flood Fill